import { Request, Response, NextFunction } from 'express';
import ApiError from '@/utils/ApiError';
import { logger } from '@/utils/logger';
import { config } from '@/config';

const errorHandler = (err: any, req: Request, res: Response, next: NextFunction) => {
  let error = err;

  // 如果不是 ApiError，转换为 ApiError
  if (!(error instanceof ApiError)) {
    const statusCode = error.statusCode || 500;
    const message = error.message || 'Internal Server Error';
    error = new ApiError(statusCode, message, false, err.stack);
  }

  // 记录错误日志
  logger.error({
    error: {
      message: error.message,
      stack: error.stack,
      statusCode: error.statusCode,
    },
    request: {
      method: req.method,
      url: req.url,
      ip: req.ip,
      userAgent: req.get('User-Agent'),
    },
  });

  // 响应错误
  const response: any = {
    success: false,
    message: error.message,
    statusCode: error.statusCode,
  };

  // 在开发环境下返回错误堆栈
  if (config.nodeEnv === 'development') {
    response.stack = error.stack;
  }

  res.status(error.statusCode).json(response);
};

export { errorHandler };